package response

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"gitee.com/layheart/gameServer/model/common"
	"net"
)

type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

const (
	Success = common.StatusOk
	Fail    = common.StatusBadRequest
)

func OkWithMessage(message string, conn net.Conn) {
	Result(Success, map[string]interface{}{}, message, conn)
}

func OkWithData(data interface{}, message string, conn net.Conn) {
	Result(Success, data, message, conn)
}

func FailWithMessage(message string, conn net.Conn) {
	Result(Fail, map[string]interface{}{}, message, conn)
}

func Result(code int, data interface{}, message string, conn net.Conn) {
	result := Response{
		Code:    code,
		Message: message,
		Data:    data,
	}

	resultJson, _ := json.Marshal(result)
	length := len(resultJson)
	lengthData := make([]byte, 4)
	binary.BigEndian.PutUint32(lengthData, uint32(length))

	lengthData = append(lengthData, resultJson...)

	// 开始时间
	_, err := conn.Write(lengthData)
	if err != nil {
		fmt.Println("err:", err)
		return
	}
}
